class Solution:
    def numOfMinutes(self, n: int, headID: int, manager: list[int], informTime: list[int]) -> int:
        # 标记节点是否已计算
        visited = [-1 for _ in range(n)]
        visited[headID] = 0

        # 计算各个节点的时间
        for i in range(n):
            # 节点已计算
            if visited[i] != -1:
                continue

            # 计算节点的值
            def dfs(number: int) -> int:
                # 节点已计算
                if visited[number] != -1:
                    return visited[number]
                # 终止条件
                if number == headID:
                    return 0
                # 记忆化标记
                visited[number] = dfs(manager[number]) + informTime[manager[number]]
                return visited[number]

            visited[i] = dfs(i)

        return max(visited)
